package com.googlecode.xcarve.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;

public class ConfigHolder implements InitializingBean{
	private Map<String, Object> configs = new HashMap<String, Object>();
	private static Map<String, Object> globalConfig = null;
	
	private ConfigHolder() {
	}
	
	public Map<String, Object> getConfigs() {
		return configs;
	}

	public void setConfigs(Map<String, Object> configs) {
		this.configs = configs;
	}

	public static int getIntValue(String key){
		return MapUtils.getIntValue(globalConfig, key);
	}
	
	public static int getIntValue(String key, int defaultValue){
		return MapUtils.getIntValue(globalConfig, key, defaultValue);
	}
	
	public static boolean getBooleanValue(String key, boolean defaultValue){
		return MapUtils.getBooleanValue(globalConfig, key, defaultValue);
	}

	public static String getStringValue(String key){
		return MapUtils.getString(globalConfig, key);
	}
	
	public static String getStringValue(String key, String defaultValue){
		return MapUtils.getString(globalConfig, key, defaultValue);
	}
	
	public static Object get(String key){
		return globalConfig.get(key);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if(CollectionUtils.isEmpty(this.configs)){
			throw new IllegalArgumentException("must set config. config must include zookeeper properties.");
		}
		if(globalConfig == null){
			globalConfig = new HashMap<String, Object>(this.configs);
		}else{
			throw new IllegalStateException("configholder instance must be single instance, "
					+ "check spring xml files ensure must only one configholder bean.");
		}
	}
	
	
}
